package juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

public class CyclicBarrierDemo {
    private static final int NUMS = 5;
    public static final CyclicBarrier cyclicBarrier = new CyclicBarrier(NUMS,new Master());

    public static void main(String[] args) {
        for (int i = 0; i < NUMS; i++) {
            Thread thread = new Thread(new Student(cyclicBarrier,i));
            thread.start();
        }
    }

    static class Student implements Runnable{
        private volatile Integer studentNo;
        private CyclicBarrier cyclicBarrier;
        public Student(CyclicBarrier cyclicBarrier, Integer studentNo){
            this.cyclicBarrier = cyclicBarrier;
            this.studentNo = studentNo;
        }
        @Override
        public void run() {
            try {
                System.out.println("学生"+studentNo+",已经上巴士");
                cyclicBarrier.await();
                System.out.println("学生"+studentNo+",巴士已经到达目的地");
                cyclicBarrier.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    }

    static class Master implements Runnable{
        private static int step = 1;

        @Override
        public void run() {
            if(step == 1){
                System.out.println("同学们都已经上大巴了，准备出发！");
            }else if(step == 2){
                System.out.println("所有大巴都到了，我们开始春游！");
            }
            step++;
        }
    }
}
